//
//  IfengOrderViewController.m
//  IfengNews
//
//  Created by Ryan on 13-7-10.
//
//

#import "IfengOrderViewController.h"
#import "CLGloble.h"
#import "IfengOrderStore.h"
#include "math.h"
#import "IfengMenuItemCell.h"
#import "ChannelComponent.h"
#import "Sgr_macro.h"
#import "NSObject+sagittarius.h"

#define ANIMATION_DURATION 0.25
#define DELAY_INTERVAL_TAP 0.5
#define DELAY_INTERVAL_MOVE 0.03
#define EXTEND_CRASH_TEST_AREA_HEIGHT 40
#define TITLEVIEW_HEIGHT (54+22)

#define CLitemHeight 47.f
#define CLitemWidth 79.f

#define CLitemY 15.f
#define CLitemRealHeight 32.f
#define CLitemRealWidth 68.f

#define CLOrderperLine 4

@interface IfengOrderViewController ()

@property (nonatomic,strong) NSMutableArray *theOrdered;
@property (nonatomic,strong)NSMutableArray *theUnOrdered;
@property (nonatomic,strong) NSMutableArray *theOrderedView;
@property (nonatomic,strong) NSMutableArray *theUnOrderedView;
@property (nonatomic,strong) UIView *unordertop;
@property (nonatomic,strong) UIView *titleView;
@property (nonatomic,strong) UIButton *toolView;
@property (nonatomic,assign) float selectViewHeight;
@property (nonatomic,strong) UIColor *activeColor;

@property (nonatomic,assign) NSTimeInterval timeInterval;
@property (nonatomic,strong) NSLock *locker;

@property (nonatomic,strong) UIView *baseView;

@property (nonatomic,strong)IfengMenuItemCell *theLasterOne;

@property (nonatomic,strong)NSDictionary *placeholder;

// 未订阅区域是否需要上下移动
- (int)_decideMoveDirection;
// 移位方法
- (void)_layoutTapItemAndItBehind4Order:(int)fromIndex andIsDirection:(int)unordertopDirection andExceptIndex:(int)exceptIndex;
- (void)_layoutTapItemAndItBehind4UnOrder:(int)fromIndex andIsDoComplate:(BOOL)doComplate andExceptIndex:(int)exceptIndex;;
- (void)_layoutAllUnorderItemsWithDirection:(int)direction andMoveLastOne:(BOOL)moveLastOne;
// 判断拖动的cell的插入位置
- (int)_confirmTheInsertIndexWithArray:(NSArray *)array forCellItem:(IfengMenuItemCell *)cellItem;
// 计算拖动的目的区域 及插入位置
- (void)_calculateDrag2OrderOrUnorderArea:(int*)areaNum andInsertIndex:(int*)insertIndex forCellItem:(IfengMenuItemCell *)cellItem;
// 同区域拖动
- (void)_adjustSameAreaItem:(IfengMenuItemCell *)cellItem isOrdered:(BOOL)isOrdered insertIndex:(int)insertIndex;
// 跨区域拖动
- (void)_adjustDiffAreaItem:(IfengMenuItemCell *)cellItem is2Order:(BOOL)is2Order insertIndex:(int)insertIndex;

@end

@implementation IfengOrderViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
      _locker = [[NSLock alloc] init];
     
    }
    return self;
}

- (void)dealloc{
    
}

- (void)viewDidLoad
{
    
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    
    self.baseView=[[UIView alloc] init];
    self.baseView.backgroundColor=[UIColor whiteColor];
    CGRect frame=self.view.bounds;
    frame.origin.y=20.f;
    self.baseView.frame=frame;
    [self.view addSubview:self.baseView];
    
  
    
    [self loadTitle];
    [self loadselected];
    [self loadUnselect];
  //  [self loadbackview];
}

- (void)addLastAdd:(int ) i  :(float)startX :(float )startY{
    if(!self.theLasterOne){
        self.theLasterOne=[[IfengMenuItemCell alloc] initWithBoderColor:[UIColor clearColor]];
        UIImageView *add=[[UIImageView alloc] init];
        add.image=[UIImage imageNamed:@"首页订阅_添加.png"];
        add.frame=self.theLasterOne.bounds;
        add.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        [self.theLasterOne addSubview:add];
        
        [self.theLasterOne setStaticYES];
        
    }else{
         self.theLasterOne.hidden=(self.theUnOrderedView.count==0);
    }
    
   
    
    
    CGRect theRect=CGRectMake(startX+((CLitemWidth-1)*(i%CLOrderperLine)),
                              startY+((CLitemHeight-1)*(i/CLOrderperLine))+CLitemY,CLitemRealWidth, CLitemRealHeight);
    self.theLasterOne.frame=theRect;
    [self.baseView addSubview:self.theLasterOne];
   

}

- (void)loadTitle{
    self.titleView=[UIView new];
    self.titleView.frame=CGRectMake(0, 0, GlobleWidth, TITLEVIEW_HEIGHT);
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] < 7.0) {
        UIView *topshadow=[UIView new];
        topshadow.frame=CGRectMake(0, 0, GlobleWidth, 5.0f);
        
        topshadow.backgroundColor=[UIColor colorWithPatternImage:
                                   sgrUIImageFile(@"order_titleShadow")];
        [self.titleView addSubview:topshadow];
    }
    UILabel *titleLabel=[UILabel new];
    titleLabel.font=[UIFont systemFontOfSize:14];
    titleLabel.frame=CGRectMake(120.0f, 33+25.0f, 80.0f, titleLabel.font.lineHeight);
    titleLabel.text=@"频道订阅";
    
    titleLabel.textColor=RGB(0xff, 0x30, 0x3b);
    titleLabel.backgroundColor=[UIColor whiteColor];
    self.titleView.backgroundColor=[UIColor whiteColor];
    [self.titleView addSubview:titleLabel];

    [self.baseView addSubview:self.titleView];
}

- (void)loadselected{
    NSArray *ordered=[[IfengOrderStore sharedInstance] getOrderedMenuItem];
    if(!ordered || ![ordered isKindOfClass:[NSArray class]]){
      ordered=[[IfengOrderStore sharedInstance] getDefaultOrderMenuItem];
    }
  
    self.theOrdered=[NSMutableArray arrayWithArray:ordered];
//    self.placeholder=[NSDictionary new];
//    [self.theOrdered sgrAddObject:self.placeholder];
    
    
    //[self.theOrdered sgrInsertObject:@{@"adID":@(-2)} atIndex:2];
    int rows=ceilf([self.theOrdered count]/(float)CLOrderperLine);
    self.selectViewHeight=rows*(CLitemHeight-1)+30.0f;// 最少也有30像素的空间
   
    self.unordertop=[UIView new];
    self.unordertop.frame=CGRectMake(0, self.selectViewHeight+TITLEVIEW_HEIGHT, GlobleWidth, 31.0f);//空开TITLEVIEW_HEIGHT的上导航title
    
//    self.unordertop.backgroundColor=[UIColor colorWithPatternImage:sgrUIImageFile(ICurrentTheme.orderStyle.orderUnselectTopName)];
    self.unordertop.backgroundColor = [UIColor clearColor];
    [self.baseView addSubview:self.unordertop];
    
//    int gengduopindaocolor=ICurrentTheme.orderStyle.gengduopindaoColor;
//    UIColor *color=[UIColor colorWithRed:((gengduopindaocolor>>16)&0x0000ff)/255.0f
//                                   green:((gengduopindaocolor>>8)&0x0000ff)/255.0f
//                                    blue:(gengduopindaocolor&0x0000ff)/255.0f
//                                   alpha:1.0f];

    UILabel *gengduopindao=[UILabel new];
    gengduopindao.frame=CGRectMake(0, 15.0f, GlobleWidth, 22.0f);
    gengduopindao.backgroundColor=RGB(234, 234, 234);
    gengduopindao.textAlignment=NSTextAlignmentCenter;
    gengduopindao.font=[UIFont systemFontOfSize:11.0f];
    gengduopindao.text=@"更多频道";
    gengduopindao.textColor=RGB(0x56, 0x56, 0x6e);
    [self.unordertop addSubview:gengduopindao];
   
    int n=[self.theOrdered count];
    float startx=13.0f;
    float starty=TITLEVIEW_HEIGHT;
   
    
    UIColor *color=RGB(0x86, 0x86, 0x86);
    float itemWidth=CLitemWidth;
    float itemHeight=CLitemHeight;
   
    self.theOrderedView=[NSMutableArray array];
    int i=0;
    for(;i<n;i++){
        IfengMenuItemCell *cell=[[IfengMenuItemCell alloc] initWithBoderColor:color];
        cell.isSelected=YES;
        cell.index=i;
       // cell.isblank=(i==2);
        
        CGRect theRect=CGRectMake(startx+((itemWidth-1)*(i%CLOrderperLine)),
                                  starty+((itemHeight-1)*(i/CLOrderperLine))+CLitemY,CLitemRealWidth, CLitemRealHeight);
//        if(i==1){
//            theRect.size.width=2*itemWidth;
//        }
        cell.frame=theRect;
        [cell reInitCompont];
        NSDictionary *dic=[self.theOrdered sgrGetDictionaryForIndex:i];
        [cell setText:[dic sgrGetStringForKey:@"channelName"]];
        
        if([@"2" isEqualToString:[dic sgrGetStringForKey:@"channelId"]]||
           [@"9" isEqualToString:[dic sgrGetStringForKey:@"channelId"]]||
           [@"8" isEqualToString:[dic sgrGetStringForKey:@"channelId"]]||
           [@"13" isEqualToString:[dic sgrGetStringForKey:@"channelId"]]){
//           [@"phtv" isEqualToString:[dic sgrGetStringForKey:@"pathId"]]||
//           [@"phtv2" isEqualToString:[dic sgrGetStringForKey:@"pathId"]]||
//           [@"disnews" isEqualToString:[dic sgrGetStringForKey:@"pathId"]]){
            [cell setStaticYES];
        }else if([@"7" isEqualToString:[dic sgrGetStringForKey:@"channelId"]]||
                 [@"10" isEqualToString:[dic sgrGetStringForKey:@"channelId"]]){
            [cell setLockArea];
        }else{
            [cell addTapTarget:self select:@selector(dotap:)];
        }
        cell.delegate = self;
        
     
      
        [self.baseView addSubview:cell];
        [self.theOrderedView addObject:cell];
    }
    [self addLastAdd:i :startx :starty];
    
}

- (void)loadUnselect{
    float pheight=self.selectViewHeight;
    NSArray *items=[[IfengOrderStore sharedInstance] getUnOrderMenuItem];
    
    self.theUnOrdered=[NSMutableArray arrayWithArray:items];
    int n=[self.theUnOrdered count];
    float startx=13.0f;
    float starty=pheight+TITLEVIEW_HEIGHT+31.0f;
    
    UIColor *color=RGB(0x86, 0x86, 0x86);
  
    float itemWidth=CLitemWidth;
    float itemHeight=CLitemHeight;
    self.theUnOrderedView=[NSMutableArray array];
    
    for (int i=0; i<n; i++) {
        IfengMenuItemCell *cell=[[IfengMenuItemCell alloc] initWithBoderColor:color];
        cell.index=i;
        cell.isSelected=NO;
        CGRect theRect=CGRectMake(startx+((itemWidth-1)*(i%CLOrderperLine)),
                                  starty+((itemHeight-1)*(i/CLOrderperLine))+CLitemY,CLitemRealWidth, CLitemRealHeight);
        cell.frame=theRect;
        [cell reInitCompont];
        [cell setText:[[self.theUnOrdered sgrGetDictionaryForIndex:i] sgrGetStringForKey:@"channelName"]];
        [self.baseView addSubview:cell];
        [cell addTapTarget:self select:@selector(dotap:)];
        cell.delegate = self;
        [self.theUnOrderedView addObject:cell];
    }
}

- (void)reloadSelectFromOrderedIndex:(int)index1 unOrderIndex:(int)index2{
  
  int unordertopDirection = [self _decideMoveDirection];
  
  // 调整订阅区域个订阅项的位置
  [self _layoutTapItemAndItBehind4Order:index1 andIsDirection:unordertopDirection andExceptIndex:-1];
  
  // 向上移动中间的白线
  if (index1 == self.theOrdered.count && unordertopDirection == -1) {
    /***
     *
     UIViewAnimationOptionCurveEaseInOut
     UIViewAnimationOptionCurveEaseIn
     UIViewAnimationOptionCurveEaseOut
     UIViewAnimationOptionCurveLinear
     ***/
    [UIView animateWithDuration:ANIMATION_DURATION delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
      [self _layoutAllUnorderItemsWithDirection:-1 andMoveLastOne:YES];
    } completion:^(BOOL finished) {}];
  }
  
  // 移动未订阅项区域 --区域大小没有变化时
  if (unordertopDirection == 0) {
    [self _layoutTapItemAndItBehind4UnOrder:index2 andIsDoComplate:NO andExceptIndex:-1];
    // 不需要移动白色分割线，则只移动item就OK了
    return;
  }
  
  // 移动中间的白色分割线 --区域大小发生变化时
  if (unordertopDirection == -1) {
    if (index1 == self.theOrdered.count) {
      // 取消的是最后一个订阅项
      [self _layoutTapItemAndItBehind4UnOrder:index2 andIsDoComplate:NO andExceptIndex:-1];
    }else{
      // 取消的并非最后一项
      [self _layoutTapItemAndItBehind4UnOrder:index2 andIsDoComplate:YES andExceptIndex:-1];
    }
  }
  else if (unordertopDirection == 1){
    [UIView animateWithDuration:ANIMATION_DURATION delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
      [self _layoutAllUnorderItemsWithDirection:unordertopDirection andMoveLastOne:YES];
    } completion:^(BOOL finished) {
      [self _layoutTapItemAndItBehind4UnOrder:index2 andIsDoComplate:NO andExceptIndex:-1];
    }];
  }
}

- (void)_layoutAllUnorderItemsWithDirection:(int)direction andMoveLastOne:(BOOL)moveLastOne{
    int n=[self.theUnOrdered count];
    float itemWidth=CLitemWidth;
    float itemHeight=CLitemHeight;
    self.unordertop.frame=CGRectMake(0, self.selectViewHeight+TITLEVIEW_HEIGHT, GlobleWidth, 31.0f);
    // 移动未订阅项
    for (int i=0; i<n; i++) {
      IfengMenuItemCell *cell=[self.theUnOrderedView sgrGetType:[IfengMenuItemCell class] forIndex:i];
      cell.index=i;
      // 这的逻辑非常乱，已经理不清了
      if (moveLastOne && direction == -1 && i == n-1) {
        continue;
      }
        
      CGRect theRect=CGRectMake(cell.frame.origin.x,cell.frame.origin.y+((itemHeight-1)*direction)+CLitemY,CLitemRealWidth,CLitemRealHeight);
       

      cell.frame=theRect;
    }
}

// 移动下面将要订阅的item以及它后面各个item
- (void)_layoutTapItemAndItBehind4UnOrder:(int)fromIndex andIsDoComplate:(BOOL)doComplate andExceptIndex:(int)exceptIndex{
  // 移动未订阅项 --选中项的后面各项
  int n = (int)[self.theUnOrdered count];
  int startx=13.0f;
  int starty=self.selectViewHeight+TITLEVIEW_HEIGHT+31.0f;
  float itemWidth=CLitemWidth;
  float itemHeight=CLitemHeight;
  
  for (int i=0; i<n; i++) {
    IfengMenuItemCell *cell=[self.theUnOrderedView sgrGetType:[IfengMenuItemCell class] forIndex:i];
    cell.index=i;
    
    CGFloat originY = starty+((itemHeight-1)*(i/CLOrderperLine));
    // 若先移动，后整体调整上移，则做动画的cellItem需要先移到下面一个位置后 在和其它item整体调整
    if (doComplate) {
      originY += itemHeight-1;
    }
    CGRect theRect=CGRectMake(startx+((itemWidth-1)*(i%CLOrderperLine)),originY+CLitemY,CLitemRealWidth, CLitemRealHeight);
    
    if (i == exceptIndex) {
      // 重置碰撞区域
      cell.crashTestRect = CGRectInset(theRect, INSET_X, INSET_Y);
      continue;
    }
    
    [UIView animateWithDuration:ANIMATION_DURATION delay:DELAY_INTERVAL_MOVE*(i-fromIndex) options:UIViewAnimationOptionCurveEaseOut animations:^{
      cell.frame=theRect;
    } completion:^(BOOL finished) {
      // 当取消订阅的item是最后一项时，不执行此方法
      if (doComplate && fromIndex < n-1) {
        [UIView animateWithDuration:ANIMATION_DURATION delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
          [self _layoutAllUnorderItemsWithDirection:-1 andMoveLastOne:YES];
        } completion:^(BOOL finished) {}];
      }
    }];
  }
}

// 移动下面还未订阅的item以及它后面各个item
- (void)_layoutTapItemAndItBehind4Order:(int)fromIndex andIsDirection:(int)unordertopDirection andExceptIndex:(int)exceptIndex{
  int n=(int)[self.theOrdered count];
  float startx=13.0f;
  float starty=TITLEVIEW_HEIGHT;
    float itemWidth=CLitemWidth;
  float itemHeight=CLitemHeight;
  // 移动已订阅项
    int i=fromIndex;
  for(;i<n;i++){
    IfengMenuItemCell *cell=[self.theOrderedView sgrGetType:[IfengMenuItemCell class] forIndex:i];
    cell.index=i;
    CGRect theRect=CGRectMake(startx+((itemWidth-1)*(i%CLOrderperLine)),
                              starty+((itemHeight-1)*(i/CLOrderperLine))+CLitemY,CLitemRealWidth, CLitemRealHeight);
//      if(i==1){
//          theRect.size.width=2*theRect.size.width;
//      }
      
    if (exceptIndex == i) {
      // 重置碰撞区域
      cell.crashTestRect = CGRectInset(theRect, INSET_X, INSET_Y);
      continue;
    }
    [UIView animateWithDuration:ANIMATION_DURATION delay:DELAY_INTERVAL_MOVE*(i-fromIndex) options:UIViewAnimationOptionCurveEaseOut animations:^{
      cell.frame=theRect;
    } completion:^(BOOL finished) {
      // 最后一个完成的时候，下面的整体向上移动
      if (unordertopDirection == -1 && i == n-1) {
        [UIView animateWithDuration:ANIMATION_DURATION delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
          [self _layoutAllUnorderItemsWithDirection:unordertopDirection andMoveLastOne:NO];
        } completion:^(BOOL finished) {}];
      }
    }];
  }
    
    [self addLastAdd:i :startx :starty];
}

- (void)loadbackview{
    self.toolView=[UIButton buttonWithType:UIButtonTypeCustom];
    self.toolView.frame=CGRectMake(GlobleWidth-56.0f, GlobleHeight-44.0f, 56.0f, 44.0f);
   // self.toolView.backgroundColor=[UIColor orangeColor];
    [self.toolView setImage:[UIImage imageNamed:@"order_back.png"] forState:UIControlStateNormal];
//    [self.toolView setImage:sgrUIImageFile(ICurrentTheme.orderStyle.orderbackName2) forState:UIControlStateHighlighted];
    [self.toolView addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.toolView];
}

- (void)back{
   // [[IfengOrderStore sharedInstance] setOrderMenuItem:self.theOrdered];
//    [[NSNotificationCenter defaultCenter] postNotificationName:IfengChangeNewsMenuNotification object:nil];
    [self.dispatchObj pop];
   // [DispatchCenter pop];
}

- (void)willPop{
    [[IfengOrderStore sharedInstance] setOrderMenuItem:self.theOrdered];
    
    if ([self determineDataDuplication]) {
      
        [[ChannelComponent onlyTopScrollView] updateItemsWithArray:[[IfengOrderStore sharedInstance] getOrderedMenuItem]];
    }
}

- (BOOL)determineDataDuplication
{
    NSArray *items = [NSArray arrayWithArray:[[IfengOrderStore sharedInstance] getOrderedMenuItem]];
    
    if ([[ChannelComponent onlyTopScrollView].channelData isEqualToArray:items]) {
        return NO;
    }
    else
        return YES;
}


- (void)dotap:(IfengMenuItemCell *)cell{
    if (fabsf(self.timeInterval - [NSDate timeIntervalSinceReferenceDate]) < DELAY_INTERVAL_TAP) {
      return;
    }
    [self.baseView bringSubviewToFront:cell];
    self.timeInterval = [NSDate timeIntervalSinceReferenceDate];
    int index=cell.index;
    if(cell.isSelected){
        NSDictionary *dic=[self.theOrdered sgrGetDictionaryForIndex:index];
        [self.theOrdered sgrRemoveForIndex:index];
        [self.theOrderedView sgrRemoveForIndex:index];
        [self.theUnOrdered sgrAddObject:dic];
        [self.theUnOrderedView sgrAddObject:cell];
        cell.isSelected=NO;
      
        [self reloadSelectFromOrderedIndex:index unOrderIndex:(int)[self.theUnOrdered count]-1];
    }else{
        NSDictionary *dic=[self.theUnOrdered sgrGetDictionaryForIndex:index];
        [self.theUnOrdered sgrRemoveForIndex:index];
        [self.theUnOrderedView sgrRemoveForIndex:index];
        
        [self.theOrdered sgrAddObject:dic];
        [self.theOrderedView sgrAddObject:cell];
        cell.isSelected=YES;
      
        [self reloadSelectFromOrderedIndex:(int)[self.theOrdered count]-1 unOrderIndex:index];
    }
}

#pragma mark --拖拽方法
- (void)dragCellItem:(IfengMenuItemCell *)cellItem{
  int insertIndex = cellItem.index;
  int isDragToOrder = 0;// 不动
  [self _calculateDrag2OrderOrUnorderArea:&isDragToOrder andInsertIndex:&insertIndex forCellItem:cellItem];
  //  NSLog(@"---- cellIndex = %d，---- insertIndex = %d",cellItem.index,insertIndex);
  // 拖拽到订阅区域
  // -- order数组自己调整位置
  if (isDragToOrder == -1 && cellItem.isSelected) {
   
    [self _adjustSameAreaItem:cellItem isOrdered:YES insertIndex:insertIndex];
  // -- 订阅，并调整位置
  }else if (isDragToOrder == -1 && !cellItem.isSelected) {
      
    [self _adjustDiffAreaItem:cellItem is2Order:YES insertIndex:insertIndex];
  }
  // 拖拽到未订阅区域
  // -- unorder数组自己调整位置
  else if (isDragToOrder == 1 && !cellItem.isSelected){
      if(!cellItem.isLockArea)
    [self _adjustSameAreaItem:cellItem isOrdered:NO insertIndex:insertIndex];
  }
  // -- 取消订阅，并调整位置
  else if (isDragToOrder == 1 && cellItem.isSelected){
     
      if(!cellItem.isLockArea)
    [self _adjustDiffAreaItem:cellItem is2Order:NO insertIndex:insertIndex];
  }
}

/**
 * @abstract 计算目的地区域及插入的位置
 * @param areaNum 目的区域值指针 0:不动 -1:已订阅区域 1:非订阅区域
 * @param insertIndex 插入位置值指针 从0开始
 * @param cellIndex 拖动的item
 * @author HouJia at 20130723
 */
- (void)_calculateDrag2OrderOrUnorderArea:(int*)areaNum andInsertIndex:(int*)insertIndex forCellItem:(IfengMenuItemCell *)cellItem{
  CGFloat unselectedHeight = ceilf([self.theUnOrdered count]/(float)CLOrderperLine)*(CLitemHeight-1);// 非订阅区域高度
  // 拖拽到已订阅区域
  if (CGRectGetMaxY(cellItem.frame) > TITLEVIEW_HEIGHT
      && CGRectGetMinY(cellItem.frame) < (TITLEVIEW_HEIGHT+self.selectViewHeight-30+EXTEND_CRASH_TEST_AREA_HEIGHT)) {
//      NSArray *orderedCopy=[self.theOrderedView copy];
//      IfengMenuItemCell *lastCell=(IfengMenuItemCell *)[orderedCopy lastObject];
      //lastCell.isTheLastOne=YES;
    *insertIndex = [self _confirmTheInsertIndexWithArray:[self.theOrderedView copy] forCellItem:cellItem];
    *areaNum = -1;
  }
  // 拖拽到非订阅区域
  else if(CGRectGetMaxY(cellItem.frame) > (TITLEVIEW_HEIGHT+self.selectViewHeight+31)
          && CGRectGetMinY(cellItem.frame) < (TITLEVIEW_HEIGHT+self.selectViewHeight+31+unselectedHeight+EXTEND_CRASH_TEST_AREA_HEIGHT)){
    *insertIndex = [self _confirmTheInsertIndexWithArray:[self.theUnOrderedView copy] forCellItem:cellItem];
    *areaNum = 1;
  }
  // 头条的位置不可替代

  if (*areaNum == -1 && *insertIndex <= 4) {
    *insertIndex = 4;

  }

    
}

/**
 * @abstract 确定左上角的位置，压多压少的问题通过cell的inset控制
 */
- (int)_confirmTheInsertIndexWithArray:(NSArray *)array forCellItem:(IfengMenuItemCell *)cellItem{
  int insertIndex = (int)array.count;
  for (int i = 0;i<array.count; i++) {
    IfengMenuItemCell *cellTemp = (IfengMenuItemCell *)[array objectAtIndex:i];
     
      if(cellItem.isTheLastOne){
          insertIndex=-1;
          break;
      }
      
    if (CGRectIntersectsRect(cellItem.frame, cellTemp.crashTestRect)) {
      insertIndex = i;
      break;
    }
  }

  return insertIndex;
}

/**
 * @abstract 移动同区域的item
 */
- (void)_adjustSameAreaItem:(IfengMenuItemCell *)cellItem isOrdered:(BOOL)isOrdered insertIndex:(int)insertIndex{
  if (cellItem.index == insertIndex) {
    return;
  }
  NSMutableArray *viewArr = nil;
  NSMutableArray *dataArr = nil;
  if (isOrdered) {
    viewArr = self.theOrderedView;
    dataArr = self.theOrdered;
  }else{
    viewArr = self.theUnOrderedView;
    dataArr = self.theUnOrdered;
  }
  // 挪移
//  IfengMenuItemCell *cellTemp = [viewArr objectAtIndex:cellItem.index];
  NSObject *objTemp = [dataArr objectAtIndex:cellItem.index];
  [viewArr removeObjectAtIndex:cellItem.index];
  [dataArr removeObjectAtIndex:cellItem.index];
  if (insertIndex >= viewArr.count) {
    [viewArr addObject:cellItem];
    [dataArr addObject:objTemp];
  }else{
    [viewArr sgrInsertObject:cellItem atIndex:insertIndex];
    [dataArr sgrInsertObject:objTemp atIndex:insertIndex];
  }
  
  int exceptionIndex = (int)[viewArr indexOfObject:cellItem];
  // 重置item下标，以备重新调整位置
  [viewArr enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    [(IfengMenuItemCell *)obj setIndex:-1];
  }];
  cellItem.index = exceptionIndex;
  // 调整非订阅区域个item位置
  if (isOrdered) {
    [self _layoutTapItemAndItBehind4Order:0 andIsDirection:0 andExceptIndex:exceptionIndex];
  }else{
    [self _layoutTapItemAndItBehind4UnOrder:0 andIsDoComplate:NO andExceptIndex:exceptionIndex];
  }
}

/**
 * @abstract 跨区域移动item
 */
- (void)_adjustDiffAreaItem:(IfengMenuItemCell *)cellItem is2Order:(BOOL)is2Order insertIndex:(int)insertIndex{
  // 挪移
  NSMutableArray *forRemoveViewArr = nil;
  NSMutableArray *forRemoveDateArr = nil;
  NSMutableArray *forInsertViewArr = nil;
  NSMutableArray *forInsertDateArr = nil;
  if (is2Order) {
    forRemoveViewArr = self.theUnOrderedView;
    forRemoveDateArr = self.theUnOrdered;
    forInsertViewArr = self.theOrderedView;
    forInsertDateArr = self.theOrdered;
  }else{
    forRemoveViewArr = self.theOrderedView;
    forRemoveDateArr = self.theOrdered;
    forInsertViewArr = self.theUnOrderedView;
    forInsertDateArr = self.theUnOrdered;
  }
  IfengMenuItemCell *cellTemp = cellItem;
  NSObject *objTemp = [forRemoveDateArr objectAtIndex:cellItem.index];
  [forRemoveViewArr removeObjectAtIndex:cellItem.index];
  [forRemoveDateArr removeObjectAtIndex:cellItem.index];
  cellItem.isSelected = is2Order;
  
  if (insertIndex >= forInsertViewArr.count) {
    [forInsertViewArr addObject:cellTemp];
    [forInsertDateArr addObject:objTemp];
  }else{
    [forInsertViewArr sgrInsertObject:cellTemp atIndex:insertIndex];
    [forInsertDateArr sgrInsertObject:objTemp atIndex:insertIndex];
  }
  
  int cellNewIndexOrder = (int)[self.theOrderedView indexOfObject:cellItem];
  cellNewIndexOrder = cellNewIndexOrder==NSNotFound?-1:cellNewIndexOrder;
  int cellNewIndexUnorder = (int)[self.theUnOrderedView indexOfObject:cellItem];
  cellNewIndexUnorder = cellNewIndexUnorder==NSNotFound?-1:cellNewIndexUnorder;
  // 重置item下标，以备重新调整位置
  [forInsertViewArr enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    [(IfengMenuItemCell *)obj setIndex:-1];
  }];
  [forRemoveViewArr enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    [(IfengMenuItemCell *)obj setIndex:-1];
  }];
  cellItem.index = cellNewIndexOrder == -1?cellNewIndexUnorder:cellNewIndexOrder;
  // 移动中间的白色分割线
  [UIView animateWithDuration:ANIMATION_DURATION delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
    [self _layoutAllUnorderItemsWithDirection:[self _decideMoveDirection] andMoveLastOne:YES];
  } completion:^(BOOL finished) {}];
  // 调整订阅与非订阅区域个item位置
  [self _layoutTapItemAndItBehind4Order:0 andIsDirection:0 andExceptIndex:cellNewIndexOrder];
  [self _layoutTapItemAndItBehind4UnOrder:0 andIsDoComplate:NO andExceptIndex:cellNewIndexUnorder];
}

- (void)setSelectViewHeight:(float)selectViewHeight{
    _selectViewHeight=selectViewHeight;
}

- (int)_decideMoveDirection{
   
  int rows=ceilf([self.theOrdered count]/(float)CLOrderperLine);
  int newSelectedHeight = rows*(CLitemHeight-1)+30.0f;
  int unordertopDirection = 0;// 不移动
  if (self.selectViewHeight > newSelectedHeight) {
    unordertopDirection = -1; // 向上移动
  }else if(self.selectViewHeight < newSelectedHeight){
    unordertopDirection = 1; // 向下移动
  }
  self.selectViewHeight = newSelectedHeight;
  return unordertopDirection;
}

- (void)dragCellItemEnd:(IfengMenuItemCell *)cellItem{
// 在这里把调整真正实施与4个数组
  
  int i = cellItem.index;
  float startx=13.0f;
  float itemWidth=CLitemWidth;
  float itemHeight=CLitemHeight;
  
  if (cellItem.isSelected) {
    float starty=TITLEVIEW_HEIGHT;
    CGRect theRect=CGRectMake(startx+((itemWidth-1)*(i%CLOrderperLine)),
                              starty+((itemHeight-1)*(i/CLOrderperLine))+CLitemY,CLitemRealWidth, CLitemRealHeight);
    [UIView animateWithDuration:ANIMATION_DURATION delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
      cellItem.frame=theRect;
    } completion:^(BOOL finished) {}];
  }else{    
    int starty=self.selectViewHeight+TITLEVIEW_HEIGHT+31.0f;
    CGRect theRect=CGRectMake(startx+((itemWidth-1)*(i%CLOrderperLine)),starty+((itemHeight-1)*(i/CLOrderperLine))+CLitemY,CLitemRealWidth, CLitemRealHeight);
    [UIView animateWithDuration:ANIMATION_DURATION delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
      cellItem.frame=theRect;
    } completion:^(BOOL finished) {}];
  }
  
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end
